﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrnMall.CacheManager;
using Newtonsoft.Json;
using StackExchange.Redis;
using System.Configuration;
using System.Diagnostics;

namespace BrnMall.CacheStrategy.Redis
{
    public class CacheStrategy : ICacheStrategy
    {
        private static readonly ConnectionMultiplexer Redis;
        private static readonly object Locker = new object();
        static CacheStrategy()
        {
            lock (Locker)
            {
                if (Redis == null)
                {
                    Redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConn"]);
                }
            }


        }

        public IDatabase GetDatabase()
        {
            return Redis.GetDatabase();
        }
        public string Name { get; }="Redis";

        private int _timeout = 300;//单位秒

        /// <summary>
        /// 缓存过期时间
        /// </summary>
        /// <value></value>
        public int TimeOut
        {
            get
            {
                return _timeout;
            }
            set
            {
                _timeout = value > 0 ? value : 3600;
            }
        }
        public T Get<T>(string key)
        {
            try
            {
                var d= GetDatabase().StringGet(key);
                if(d.HasValue)
                return JsonConvert.DeserializeObject<T>(d);
            }
            catch (Exception e)
            {
                Trace.TraceInformation(e.Message);
            }
            return default(T);

        }

        public void Remove(string key)
        {
            try
            {
                GetDatabase().KeyDelete(key);
            }
            catch (Exception e)
            {
                Trace.TraceInformation(e.Message);
            }
           
        }

        

        public void Clear()
        {

        }

        public bool Exists(string key)
        {
            try
            {
                return GetDatabase().KeyExists(key);
            }
            catch (Exception e)
            {
                Trace.TraceInformation(e.Message);
            }
            return false;

        }

        public void Insert<T>(string key, T data)
        {
            try
            {
                GetDatabase().StringSet(key, JsonConvert.SerializeObject(data));
            }
            catch (Exception e)
            {

                Trace.TraceInformation(e.Message);
            }
           
        }

        public void Insert<T>(string key, T data, int cacheTime)
        {
            try
            {
                GetDatabase().StringSet(key, JsonConvert.SerializeObject(data), TimeSpan.FromSeconds(cacheTime));
                
            }
            catch (Exception e)
            {

                Trace.TraceInformation(e.Message);
            }
            
        }
    }
}
